/**
 * 
 */
package billing;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collections;

/**
 * The table of Price-Steps
 * @author Gernot
 *
 */
public class PriceSteps implements Serializable {
    private static final long serialVersionUID = 5689808787548725131L;
    private ArrayList<PriceStep> steps = new ArrayList<PriceStep>();

    
    /**
     * Adds a new Price Step
     * @param startPrice
     * @param endPrice
     * @param fixedPrice
     * @param variablePricePercent
     * @return
     * @throws RemoteException when Invalid PriceStep or Overlap
     */
    public boolean addPriceStep(double startPrice, double endPrice, double fixedPrice,
            double variablePricePercent) throws RemoteException {
        return addPriceStep(new PriceStep(startPrice, endPrice, fixedPrice,variablePricePercent));
    }
    
    /**
     * Adds a new Price Step
     * @param ps
     * @return
     * @throws RemoteException when Overlap
     */
    public boolean addPriceStep(PriceStep ps) throws RemoteException{
        boolean b = false;
        for (PriceStep p : steps){
            if (p.overlaps(ps)){
                b = true;
                break;
            }
        }
        if (!b){
            this.steps.add(ps);            
            Collections.sort(steps);
        } else {
            throw new RemoteException("Price Intervall overlaps!");
        }
        return false;
    }
    
    /**
     * Removes a Price-Step intervall, returns success as boolean
     * @param startPrice
     * @param endPrice
     * @return
     * @throws RemoteException 
     */
    public boolean removePriceStep(double startPrice, double endPrice) throws RemoteException{
        boolean removed = false;
        for (PriceStep ps: this.steps){
            if (ps.isSameIntervall(startPrice, endPrice)){
                steps.remove(ps);
                removed=true;
                break; //Only 1 PriceStep can be equal!
            }
        } 
        
        if (!removed){
            throw new RemoteException("Price Intervall does not exist");
        }
        
        return removed;
    }
    
    
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        
        sb.append("Intervall\tFixed Part\tVariable Part").append("\n");
        
        for (PriceStep ps : steps){
            sb.append(ps.toString()).append("\n");
        }
                
        return sb.toString();
    }

    public ArrayList<PriceStep> getSteps() {
        return steps;
    }
    
}
